﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Collections.ObjectModel;
using Csla.Server.Hosts;
using System.Windows.Media.Animation;
using Microsoft.Win32;
using System.Configuration;
using System.IO;
using System.Diagnostics;

namespace OpenExpressApp.Server.WPFHost
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class HostWindow : Window
    {
        private Storyboard iconAnimation;
        private ObservableCollection<string> logs = new ObservableCollection<string>();
        private ServiceHost _selfHost;
        private bool manualClose;
        private bool _started;

        public HostWindow()
        {
            InitializeComponent();
            iconAnimation = Resources["IconAnimation"] as Storyboard;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.Start();
            this.Hide();
        }
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.Hide();
            e.Cancel = this.manualClose == false;
        }
        private void Window_Closed(object sender, EventArgs e)
        {
            this.Stop();
        }
        private void Window_StateChanged(object sender, EventArgs e)
        {
            if (WindowState.Minimized == WindowState)
            {
                this.ShowInTaskbar = false;
            }
        }
        private void ShowHostWindow(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Normal;
            this.ShowInTaskbar = true;
        }
        private void MIConfig_Click(object sender, RoutedEventArgs e)
        {
            this.BeginConfig();
        }
        private void StartService(object sender, RoutedEventArgs e)
        {
            this.Start();
        }
        private void StopService(object sender, RoutedEventArgs e)
        {
            this.Stop();
        }
        private void CloseHostWindow(object sender, RoutedEventArgs e)
        {
            this.manualClose = true;
            this.Close();
        }


        public void Start()
        {
            if (this._started == false)
            {
                this._selfHost = new ServiceHost(typeof(OpenExpressApp.Server.WPFHost.MultiThreadWCFPortal));
                try
                {
                    //通过配置文件配置服务
                    this._selfHost.Open();

                    log.ItemsSource = logs;
                    this.logs.Add("指标服务已启动！");
                    this.iconAnimation.Begin(this, true);

                    this._started = true;
                }
                catch (CommunicationException cs)
                {
                    this.logs.Add("异常:" + cs.Message);
                    this._selfHost.Abort();
                    this.iconAnimation.Stop(this);
                }
            }
        }
        public void Stop()
        {
            if (this._started)
            {
                this._selfHost.Close();
                this.iconAnimation.Stop(this);
                this._started = false;
            }
        }

        private new void Hide()
        {
            this.WindowState = WindowState.Minimized;
            this.ShowInTaskbar = false;
        }
        /// <summary>
        /// 打开一个对话框，选择连接字符串
        /// </summary>
        /// <param name="settings"></param>
        /// <returns></returns>
        private bool SelectDataBase(out ConnectionStringSettings settings)
        {
            settings = null;

            SelectDataBaseDialog dbDialog = new SelectDataBaseDialog();
            dbDialog.Owner = this;
            var result = dbDialog.ShowDialog();

            if (result == false)
            {
                return false;
            }

            string settingsName = dbDialog.SelectedSettingsName;
            settings = ConfigurationManager.ConnectionStrings[settingsName];
            return true;
        }
        private void BeginConfig()
        {
            ConfigWindow window = new ConfigWindow();
            var result = window.ShowDialog();
            if (result == true)
            {
                var needReboot = MessageBox.Show("重启服务后生效。\n\r是否立即重启服务？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No);
                if (needReboot == MessageBoxResult.Yes)
                {
                    //string fileName = Process.GetCurrentProcess().MainModule.FileName;
                    string fileName = System.Reflection.Assembly.GetExecutingAssembly().Location;
                    Application.Current.Shutdown();
                    Process.Start(fileName);
                }
                //this.Stop();
                //this.Start();
            }
        }
    }
}
